<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use app\wechat\controller\User;
use think\Db;



/**
 * Class UserController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   => '管理组',
 *     'action' => 'default',
 *     'parent' => 'user/AdminIndex/default',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   => '',
 *     'remark' => '管理组'
 * )
 */
class UserController extends AdminBaseController
{

    public function wechat(){

        $where = [];
        $user_login = $this->request->param('user_login');
        if(!empty($user_login)){
            $where['user_login'] = ['like',"%".$user_login."%"];
        }
        $users = Db::name('member')
            ->alias('a')
            ->join(' cmf_wechat_department_user c','c.user_id=a.openid')
            ->join(' cmf_wechat_department d','d.id=c.department_id')
            ->where($where)
            ->field('a.id,a.user_login,a.mobile,d.name')
            -> order("id")
            -> paginate(13,false,['query'=>['user_login'=>$user_login]]);
        $this->assign("users", $users);
        $this->assign("page", $users->render());
        return $this->fetch();
    } 
    public function getTag(){

        ini_set('max_execution_time', 0);
        $user = new User();
        $id = Db::name('wechat_tag')->column('tagid');
        $datatag = $user->batchTagUserList($id);
        $b = 0;
        foreach ($datatag as $key => $value) {
            foreach ($value as $k => $v) {
                $datas[$b]['tagid'] = $key;
                $datas[$b]['userid'] = $v['userid']; 
                $b++;
            }
        }
        print_r($datas);

    }
    public function wechatupdate()
    {
        ini_set('max_execution_time', 0);
        
        $content = '区纪委监委、区委办公室、区委组织部、区委宣传部、区委统战部、区委政法委、区编委办公室、区直属机关党委、区信访局、区府办公室、区财政局、区招商办、琶洲管委会、区机关事务局、区人大、区政协、区总工会、团区委、区妇联、区侨联';
        $content = explode('、',$content);
        $ids = Db::name('wechat_department')->where('name','in',$content)->order('id')->column('id');

        $user = new User();
        $data = $user->batchUserList($ids);
        $i = 0;

        $user_datas = $user_part_datas = $datas = [];
        foreach($data as $k=>$v){
            $user_datas[$i]['user_login'] = $v['name']?:'';
            $user_datas[$i]['mobile'] = $v['mobile']?:'';
            $user_datas[$i]['openid'] = $v['userid']?:'';
            $member = Db::name('member')->field('id')->where('openid',$user_datas[$i]['openid'])->find();
            if($member){
                Db::name('member')->where(['id'=>$member['id']])->update([
                    'mobile'=>$user_datas[$i]['mobile'],
                    'user_login'=>$user_datas[$i]['user_login']
                ]);
            }else{
                Db::name('member')->insert($user_datas[$i]);
            }   
            $i++;
        }
        $user_part_datas = [];
        $j = 0;
        foreach($data as $k=>$v){
            foreach($v['department'] as $value){
                $user_part_datas[$j]['user_id'] = $v['userid'];
                $user_part_datas[$j]['department_id'] = $value;
                $j++;
            }
        }

        // $id = Db::name('wechat_tag')->column('tagid');
        // $datatag = $user->batchTagUserList($id);
        // $b = 0;
        // foreach ($datatag as $key => $value) {
        //     foreach ($value as $k => $v) {
        //         $datas[$b]['tagid'] = $key;
        //         $datas[$b]['userid'] = $v['userid']; 
        //         $b++;
        //     }
        // }
        //Db::execute('truncate table cmf_member');
        Db::execute('truncate table cmf_wechat_department_user ');
        //Db::execute('truncate table cmf_wechat_tag_user');
        $res1 = Db::name('wechat_department_user')->insertAll($user_part_datas);
        //$res2 = Db::name('member')->insertAll($user_datas);
        //$res3 = Db::name('wechat_tag_user')->insertAll($datas);
        if ( $res1  ) {
            admin_log('', '更新', '企业微信用户');
            $result = ['status'=>0,'msg'=>'更新用户ok'];
            echo json_encode($result);return;
        }else{
            $result = ['status'=>1,'msg'=>'更新用户fail'];
            echo json_encode($result);return;
        }
    }

    //标签权限管理
    public function tag()
    {
        $info = Db::name('wechat_tag')->select();
        $this->assign('data',$info);
        return $this->fetch();
    }
    public function user_tag()
    {
        $id = $this->request->param('id',0,'intval');
        $info = Db::name('wechat_tag_user')
        ->alias('a')
        ->join('member c','a.userid=c.openid')
        ->field('c.user_login,a.*')
        ->where(['a.tagid'=>$id])
        ->select();
        $this->assign('data',$info);
        return $this->fetch();
    }
    public function user_tag_add()
    {
        
        $content = '区纪委监委、区委办公室、区委组织部、区委宣传部、区委统战部、区委政法委、区编委办公室、区直属机关党委、区信访局、区府办公室、区财政局、区招商办、琶洲管委会、区机关事务局、区人大、区政协、区总工会、团区委、区妇联、区侨联';
        $content = explode('、',$content);
        $ids = Db::name('wechat_department')
        ->alias('a')
        ->join('wechat_department_user b','a.id=b.department_id')
        ->join('member c','b.user_id=c.openid')
        ->where('a.name','in',$content)
        ->column('c.openid,c.user_login');

        $this->assign('data',$ids);
        return $this->fetch();
    }
    public function user_tag_addPost()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $res = Db::name('wechat_tag_user')
            ->where(['userid'=>$data['openid'],'tagid'=>$data['tagid']])
            ->find();
            if ($res) {
                $this->error('用户已属于该标签，不可重复');
            }
            $result = Db::name('wechat_tag_user')
            ->insert(['userid'=>$data['openid'],'tagid'=>$data['tagid']]);
            if ($result) {
                admin_log('', 'add', '前台用户权限');
                $this->success('添加成功');
            }else{
                $this->error('用户已属于该标签，不可重复');
            }
        }
    }
    public function user_delete()
    {
        $id = $this->request->param('id', 0, 'intval');

        $res = Db::name("wechat_tag_user")->where(["id" => $id])->delete();
        if ($res) {
            //操作日志
            admin_log('', 'delete', '前台用户权限');
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }
    /**
     * 管理员列表
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $param = $this->request->param();
        $where = ["user_type" => 1];
        /**搜索条件**/
        $user_login = $this->request->param('user_login');
        $user_email = trim($this->request->param('user_email'));

        if ($user_login) {
            $where['user_login'] = ['like', "%$user_login%"];
        }

        if ($user_email) {
            $where['user_email'] = ['like', "%$user_email%"];
        }
        // $users = Db::name('user')
        //       -> alias('u')
        //       -> field('u.*,r.name')
        //       -> join('__ROLE_USER__ ru','u.id = ru.user_id')
        //       -> join('__ROLE__ r','ru.role_id = r.id')
        //       -> where($where)
        //       -> order("u.id DESC")
        //       -> paginate(10);

        $roles = db('role')->column('name', 'id');
        
		$where['id'] = ['neq', "2"]; //去除超管的显示
		
        $users = Db::name('user')
              -> where($where)
              -> order("id DESC")
              -> paginate(10);

        $datas = $users->items();
        foreach ($datas as $k => &$v) {
            $roleNames = db('role_user')->where('user_id',$v['id'])->column('role_id');
            $names     = '';
            foreach ($roleNames as $val) {
                $names .= $roles[$val].',';
            }

            $v['name'] = trim($names, ',');
        }

        //追加请求参数到分页按钮
        $users->appends($param);

        // $rolesSrc = Db::name('role')->select();
        // $roles    = [];
        // foreach ($rolesSrc as $r) {
        //     $roleId           = $r['id'];
        //     $roles["$roleId"] = $r;
        // }
        // $this->assign("roles", $roles);

        $this->assign("users", $datas);
        $this->assign("page", $users->render());

        $actions = ['add', 'edit', 'delete', 'ban', 'cancelBan'];
        $this->assign('actions', actions_check('admin/User/', $actions));
        // pre($actions,1);
        return $this->fetch();
    }

    /**
     * 管理员操作日志
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     */
    public function operation_log()
    {   
        $where = [
            "user_type" => 1,
            'site_id'   => get_site_id(),
        ];
        /**搜索条件**/
        $user_login = $this->request->param('user_login');
        

        if ($user_login) {
            $where['user_login'] = ['like', "%$user_login%"];
        }

        $join = [
            ['__USER__ u', 'l.user_id = u.id']
        ];
        
        $field = 'l.*,u.user_login';

		$where['user_id'] = ['neq',2]; //去除超管的日志显示
		
        $log_list = Db::name('admin_log')->alias('l')
            ->join($join)
            ->field($field)
            ->where($where)
            ->order("log_time DESC")
            ->paginate(10);


        // 获取分页显示
        $page = $log_list->render();

       
        $this->assign("page", $page);
  
        $this->assign("log_list", $log_list);
        return $this->fetch();
    }


    /**
     * 管理员登录日志
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     */
    public function login_log()
    {   
        $where = ["user_type" => 1];
        /**搜索条件**/
        $user_login = $this->request->param('user_login');
        

        if ($user_login) {
            $where['user_login'] = ['like', "%$user_login%"];
        }

		$where['user_id'] = ['neq',2]; //去除超管的日志显示
		
        $join = [
            ['__USER__ u', 'l.user_id = u.id']
        ];
        
        $field = 'l.*,u.user_login';

        $log_list = Db::name('login_log')->alias('l')
            ->join($join)
            ->field($field)
            ->where($where)
            ->order("login_time DESC")
            ->paginate(10);
         

        // 获取分页显示
        $page = $log_list->render();

       
        $this->assign("page", $page);
  
        $this->assign("log_list", $log_list);
        return $this->fetch();
    }
    

    /**
     * 登录日志删除
     * @adminMenu(
     *     'name'   => '登录日志删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '登录日志删除',
     *     'param'  => ''
     * )
     */
    public function login_delete()
    {
        $param           = $this->request->param();

        
        if (isset($param['ids'])) {
          
            $ids     = $this->request->param('ids/a');
          
            $recycle = Db::name('login_log')->where(['log_id' => ['in', $ids]])->select();

            if (Db::name('login_log')->where(['log_id' => ['in', $ids]])->delete()) {
                //操作日志
                admin_log('', 'delete', '登录日志');

                $this->success("删除成功！", '');
            }
        }
    }


    /**
     * 操作日志删除
     * @adminMenu(
     *     'name'   => '操作日志删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '操作日志删除',
     *     'param'  => ''
     * )
     */
    public function operation_delete()
    {
        $param           = $this->request->param();
        
        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = Db::name('admin_log')->where(['log_id' => ['in', $ids]])->select();

            if (Db::name('admin_log')->where(['log_id' => ['in', $ids]])->delete()) {
                $this->success("删除成功！", '');
            }
        }
    }

    /**
     * 管理员添加
     * @adminMenu(
     *     'name'   => '管理员添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $roles = Db::name('role')->where(['status' => 1])->order("id DESC")->select();
        $this->assign("roles", $roles);
        return $this->fetch();
    }

    /**
     * 管理员添加提交
     * @adminMenu(
     *     'name'   => '管理员添加提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                $role_ids = $_POST['role_id'];
                unset($_POST['role_id']);
                $result = $this->validate($this->request->param(), 'User');
                if ($result !== true) {
                    $this->error($result);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                    $result             = DB::name('user')->insertGetId($_POST);
                    if ($result !== false) {
                        //$role_user_model=M("RoleUser");
                        foreach ($role_ids as $role_id) {
                            if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            Db::name('RoleUser')->insert(["role_id" => $role_id, "user_id" => $result]);
                        }

                        //操作日志
                        admin_log('', 'add', '管理员');

                        $this->success("添加成功！", url("user/index"));
                    } else {
                        $this->error("添加失败！");
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 管理员编辑
     * @adminMenu(
     *     'name'   => '管理员编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id    = $this->request->param('id', 0, 'intval');
        $roles = DB::name('role')->where(['status' => 1])->order("id DESC")->select();
        $this->assign("roles", $roles);
        $role_ids = DB::name('RoleUser')->where(["user_id" => $id])->column("role_id");
        $this->assign("role_ids", $role_ids);

        $user = DB::name('user')->where(["id" => $id])->find();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 管理员编辑提交
     * @adminMenu(
     *     'name'   => '管理员编辑提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                if (empty($_POST['user_pass'])) {
                    unset($_POST['user_pass']);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                }
                $role_ids = $this->request->param('role_id/a');
                unset($_POST['role_id']);
                $result = $this->validate($this->request->param(), 'User.edit');

                if ($result !== true) {
                    // 验证失败 输出错误信息
                    $this->error($result);
                } else {
                    $result = DB::name('user')->update($_POST);
                    if ($result !== false) {
                        $uid = $this->request->param('id', 0, 'intval');
                        DB::name("RoleUser")->where(["user_id" => $uid])->delete();
                        foreach ($role_ids as $role_id) {
                            if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            DB::name("RoleUser")->insert(["role_id" => $role_id, "user_id" => $uid]);
                        }

                        //操作日志
                        admin_log('', 'edit', '管理员');

                        $this->success("保存成功！");
                    } else {
                        $this->error("保存失败！");
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 管理员个人信息修改
     * @adminMenu(
     *     'name'   => '个人信息',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改',
     *     'param'  => ''
     * )
     */
    public function userInfo()
    {
        $id   = cmf_get_current_admin_id();
        $user = Db::name('user')->where(["id" => $id])->find();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 管理员个人信息修改提交
     * @adminMenu(
     *     'name'   => '管理员个人信息修改提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改提交',
     *     'param'  => ''
     * )
     */
    public function userInfoPost()
    {
        if ($this->request->isPost()) {

            $data             = $this->request->post();
            $data['birthday'] = strtotime($data['birthday']);
            $data['id']       = cmf_get_current_admin_id();
            $create_result    = Db::name('user')->update($data);;
            if ($create_result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    /**
     * 管理员删除
     * @adminMenu(
     *     'name'   => '管理员删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error("最高管理员不能删除！");
        }

        if (Db::name('user')->delete($id) !== false) {
            Db::name("RoleUser")->where(["user_id" => $id])->delete();

            //操作日志
            admin_log('', 'delete', '管理员');

            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 停用管理员
     * @adminMenu(
     *     'name'   => '停用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '停用管理员',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id     = $this->request->param('id', 0, 'intval');
        $cancel = $this->request->param('cancel', 0, 'intval');

        if( $cancel == 0 ){
            if (!empty($id)) {
                $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '1');
                if ($result !== false) {
                    $this->success("操作成功！", url("user/index"));
                } else {
                    $this->error('操作失败！');
                }
            } else {
                $this->error('数据传入失败！');
            }
        }

        if (!empty($id)) {
            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '0');
            if ($result !== false) {
                //操作日志
                admin_log('', '', '拉黑管理员');

                $this->success("操作成功！", url("user/index"));
            } else {
                $this->error('操作失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 启用管理员
     * @adminMenu(
     *     'name'   => '启用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '启用管理员',
     *     'param'  => ''
     * )
     */
    // public function cancelBan()
    // {
    //     $id = $this->request->param('id', 0, 'intval');
    //     if (!empty($id)) {
    //         $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '1');
    //         if ($result !== false) {
    //             $this->success("管理员启用成功！", url("user/index"));
    //         } else {
    //             $this->error('管理员启用失败！');
    //         }
    //     } else {
    //         $this->error('数据传入失败！');
    //     }
    // }


}
